1. Introduction
In the remainder of the document, the computer will be referred to as ‘the host’ and any external hardware capable of being connected to the host through a USB or PS/2 port (including keyboard and key-stroke monitoring hardware) will be referred to as a ‘device’.
The PS-2 serial bus interface is the ubiquitous method by which a keyboard is connected to a PC computer. Other, less commonly used technologies are the RS-232 bus and USB (Universal Serial Bus).
The term “Keystroke data” is used in the specification to refer to the make and a break codes sent from a keyboard to a connected device in response to activation of a key of a keyboard.
The term “status signals” is used in the specification to refer to any status commands or data that may be sent from the host to a device which are capable of encoding a data stream (but excludes make or break codes as these cannot be sent from the host to a device).
2. The PS/2 Interface
The PS/2 device interface was developed by IBM and originally appeared in the IBM Technical Reference Manual. The physical PS/2 port is one of two styles of connectors: the 5-pin DIN or the 6-pin mini-DIN. Both connectors are electrically similar; the only practical difference between the two is the arrangement of pins, the two can be made compatible with adaptors. The pinouts for a 5-pin DIN are shown in FIG. 1a and those for a 6-pin mini-DIN are shown in FIG. 1b. 
2.1 The Electrical Interface
Vcc/Ground provide power to the keyboard.                Summary: Power Specifications        Vcc=+5V.        Max Current=100 mA.        
The Data and Clock lines are both open-collector with pull-up resistors to +5V. An “open-collector” interface has two possible states: low, or high impedance. In the “low” state, a transistor pulls the line to ground level. In the “high impedance” state, the interface acts as an open circuit and does not drive the line low or high. Furthermore, a “pullup” resistor is connected between the bus and Vcc so the bus is pulled high if none of the devices on the bus are actively pulling it low. The exact value of this resistor is not too important (1˜10 kOhms); larger resistances result in less power consumption and smaller resistances result in a faster rise time. A general open-collector interface is shown in FIG. 2.
Data and Clock are read on the microcontroller's pins A and B, respectively. Both lines are normally held at +5V, but can be pulled to ground by asserting logic “1” on C and D. As a result, Data equals D, inverted, and Clock equals C, inverted.
2.2 PS-2 Communication: General Description
The PS/2 keyboard implements a bi-directional synchronous serial protocol. The bus is “idle” when both lines are high (open-collector). This is the only state where the keyboard is allowed to begin transmitting data. The host has ultimate control over the bus and may inhibit communication at any time by pulling the Clock line low. The device always generates the clock signal. If the host wants to send data, it must first inhibit communication from the keyboard by pulling Clock low. The host then pulls Data low and releases Clock. This is the “Request-to-Send” state and signals the keyboard to start generating clock pulses.                Summary: Bus States        Data=high, Clock=high: Idle state.        Data=high, Clock=low: Communication Inhibited.        Data=low, Clock=high: Host Request-to-Send        
All data is transmitted one byte at a time and each byte is sent in a frame consisting of 11-12 bits. These bits are:                1 start bit. This is always 0.        8 data bits, least significant bit first.        1 parity bit (odd parity).        1 stop bit. This is always 1.        1 acknowledge bit (host-to-device communication only)        
The parity bit is set if there is an even number of 1's in the data bits and reset (0) if there is an odd number of 1's in the data bits. The number of 1's in the data bits plus the parity bit always adds up to an odd number (odd parity). This is used for error detection. The keyboard must check this bit and if incorrect it should respond as if it had received an invalid command. Data sent from the keyboard to the host is read on the falling edge of the clock signal; data sent from the host to the keyboard is read on the rising edge. The clock frequency must be in the range 10-16.7 kHz. This means clock must be high for 30-50 microseconds and low for 30-50 microseconds. The keyboard always generates the clock signal, but the host always has ultimate control over communication.
2.3 Communication: Device-to-Host
The Data and Clock lines are both open collector. A resistor is connected between each line and +5V, so the idle state of the bus is high. When the keyboard wants to send information, it first checks the Clock line to make sure it is at a high logic level. If it is not, the host is inhibiting communication and the keyboard must buffer any to-be-sent data until the host releases Clock. The Clock line must be continuously high for at least 50 microseconds before the keyboard can begin to transmit its data. Here is an illustrated example of an 11-bit frame from the PS/2 communications protocol:                1 start bit. This is always 0.        8 data bits, least significant bit first.        1 parity bit (odd parity).        1 stop bit. This is always 1.        
The keyboard writes a bit on the Data line when Clock is high, and the host reads it when Clock is low. FIGS. 3 and 4 illustrate this.
The Data line changes state when Clock is high and that data is valid when Clock is low. The clock frequency is 10-16.7 kHz. The time from the rising edge of a clock pulse to a data transition must be at least 5 microseconds. The time from a data transition to the falling edge of a clock pulse must be at least 5 microseconds and no greater than 25 microseconds. The host may inhibit communication at any time by pulling the Clock line low for at least 100 microseconds. If a transmission is inhibited before the 11th clock pulse, the keyboard must abort the current transmission and prepare to retransmit the current packet of data when host releases Clock. A packet of data could be, for example, a two-frame <break code>. If a keyboard is interrupted while sending the second byte of the two-frame break code, it will need to retransmit both frames of that break code, not just the frame that was interrupted. If the host pulls clock low before the first high-to-low clock transition, or after the falling edge of the last clock pulse, the keyboard/mouse does not need to retransmit any data. However, if new data is created that needs to be transmitted, it will have to be buffered until the host releases Clock. (Keyboards have a 16-byte buffer for this purpose. If more than 16 bytes worth of keystrokes occur, further keystrokes will be ignored until there is room in the buffer).
2.4 Host-to-Keyboard Communication
The packet is sent a little differently in a host-to-keyboard communication. The PS/2 keyboard always generates the clock signal. If the host wants to send data, it must first put the Clock and Data lines in a “Request-to-send” state as follows:                Inhibit communication by pulling Clock low for at least 100 microseconds.        Apply “Request-to-send” by pulling Data low, and then release Clock.        
The keyboard should check for this state at intervals not to exceed 10 milliseconds. When the keyboard detects this state, it will begin generating Clock signals and clock in eight data bits and one stop bit. The host changes the Data line only when the Clock line is low, and the keyboard reads data when Clock is high. This is opposite of what occurs in device-to-host communication. After the stop bit is received, the keyboard will acknowledge the received byte by bringing the Data line low and generating one last clock pulse. If the host does not release the Data line after the 11th clock pulse, the keyboard will continue to generate clock pulses until the Data line is released (the device will then generate an error.) The host may abort transmission at time before the 11th clock pulse (acknowledge bit) by holding Clock low for at least 100 microseconds.
Here are the steps the host must follow to send data to a PS/2 keyboard device:
1) Bring the Clock line low for at least 100 microseconds.
2) Bring the Data line low.
3) Release the Clock line.
4) Wait for the device to bring the Clock line low.
5) Set/reset the Data line to send the first data bit
6) Wait for the device to bring Clock high.
7) Wait for the device to bring Clock low.
8) Repeat steps 5-7 for the other seven data bits and the parity bit
9) Release the Data line.
10) Wait for the device to bring Data low.
11) Wait for the device to bring Clock low.
12) Wait for the device to release Data and Clock
FIG. 4 shows this graphically and FIG. 5 separates the timing to show which signals the host generates, and which does the PS/2 device generate. Illustrated in FIG. 5. part (a) the host requests to transmit data by pulling clock line low. In part (b) the keyboard generates the clocking signal and the host sends the data.
2.5 PS/2 Data Formatting
The purpose of a keyboard using the PS/2 protocol is to communicate to the PC which keys are being pressed down and when they are released. It does this in two parts. The keyboard sends one packet of data when a key is pressed down (called a ‘make’ scan code), and another when it is released (called a ‘break’ scan code). Examples of these are given in Table 1 below:
TABLE 1Examples of Scan Codes produced on Standard PS/2 Keyboard.Key PressedMake CodeBreak CodeA1CF0 1CB32F0 32Ctrl 14F0 14F1009F0 09PgUpE0 7DE0 F0 7D2.6 Current Methods of Keystroke Retrieval Via PS/2
As at the current state-of-the-art, the devices' method of retrieval via the PC keyboard PS/2 plug involves sending all keystroke information down the keyboard PS/2 line as complete keystrokes, including the ‘make’ scan code and ‘break’ scan codes. This method conforms with the industry standard specifications for keyboard to PC communications. Current devices essentially mimic a user typing the keystrokes at speed on a standard keyboard.
3. USB Bus Basics
The Universal Serial Bus (USB) provides a common means of attaching peripherals to a computer system. It has been designed to replace legacy busses such as the RS-232 and PS/2. The USB bus provides a limited power supply to peripherals as well as a mechanism for bi-directional data transfer.
3.1 Terminology
USB is a means of connecting devices to a computer host (USB host). Multiple devices are connected onto the bus with the use of USB hub devices. The USB host often has a root hub allowing multiple devices to be connected directly to the computer. Data transfers from the USB host to devices are regarded as downstream transfers with upstream transfers going from device to host. FIG. 6 gives an overview of a typical USB system.
3.2 Electrical Signalling
USB has to offer high-speed signalling over a short (shielded) cable; this is accomplished through the use of differential signalling. Differential signalling works by sending opposing signals down each wire of the USB signalling pair; this improves performance by reducing noise and allows faster data transfers. Single ended signalling (setting both wires in the pair to the same value) is used in combination with differential signalling to perform handshaking duties. USB uses half-duplex transfers over the signalling pair; this ensures only one device (be it host or peripheral) drives the bus at any given time. All transfers are host initiated in a master-slave arrangement—the host indicates when a slave device may drive the bus.
3.3 Data Encoding
To ensure acceptable signalling performance NRZI (Non Return Zero Inverted) coding is required. In addition, as no clock indicating each successive bit is used (the clock is recovered from the data) extra information is embedded into the data-stream to encode that information. The discussion of these topics is out of the scope of this document and is well described in [2].
3.4 Packet Structure
USB transfers data in packets. A packet is simply an arbitrary amount of data with a fixed structure and end of packet indication. In this case, each packet has a defined header specifying the type of transfer and often the device to which the data is sent.
FIG. 7 shows the structure of a USB data packet. Each packet has 8 synchronisation bits sent—these are used to align the data in the receiver properly and ensure reliable data transmission. The next part of the packet is the packet identifier (PID), this indicates the type of packet being sent and is comprised of 4 bits then those 4 bits repeated and inverted (allowing error detection). Following that is optional extra data comprising the packet payload and finally a mandatory end-of-packet indication (EOP) using single ended signalling. USB 1.1 defines 10 packet types [1], these are shown in Table 1.
TABLE 1USB packet types.PIDPacket TypeCategory0101SOFToken1101SETUPToken1001INToken0001OUTToken0011DATA0Data1011DATA1Data0010ACKHandshake1010NAKHandshake1110STALLHandshake1100PRESpecialRestReservedN/A
Token packets are used by the host to indicate to devices when to drive the bus (or listen for data). Data packets are used for transferring data and handshaking packets to ensure successful data delivery. The special packet is for backward compatibility with low-speed USB systems—they are used to put the USB in slow-speed mode. Further discussion of special packets is outside the scope of this document. USB 2.0 also adds the NYET handshaking packet (see [1]).
3.5 Transactions
USB transactions are made up of a number of packets in a predefined sequence. USB defines 4 major modes of communication. Control, Bulk, Interrupt, and Isochronous. Bulk and Isochronous transactions are outside the scope of this document.
Interrupt transfers are typically used by devices such as keyboards and mice that must transfer small amounts of data frequently. FIG. 8 shows 3 such interrupt transactions. In each case the host initiates the transfer with a token packet, data is sent (by either host or device depending on IN/OUT), successful transmission is acknowledged. Unsuccessful transmission or data not being ready are signalled with NAK packets.
Control transfers are more complicated and use a 3-stage approach. The host sends a SETUP packet, followed by an 8-byte (setup) data packet; and the device must acknowledge this. If required, further data packets are transferred using the same form of packet handshaking as interrupt data transfers (note multiple transfers may be needed to provide all the data). Note that the data transfer must either be a read (IN) or write (OUT) no mixing is possible. Following the (optional) data transfer, control status is exchanged using a zero-length packet for acknowledge and NAK for failure. The host acknowledges control reads, the device acknowledges control writes and also no data transfer (just setup). There are a number of standard control requests to a device and these are listed in Table 2. The requests are sent as part of the setup data packet and are used to perform initial device configuration.
TABLE 2SETUP packet requests.RequestActionGetStatusReturn current statusClearFeatureClear specified featureSetFeatureSet specified featureSetAddressSet the USB address the device communicatesonGetDescriptorGet the device descriptorSetDescriptorSet device descriptorGetConfigurationGet configuration number (or 0 if notconfigured)SetConfigurationSet configuration to that specifiedGetInterfaceGet current interfaceSetInterfaceSet interface for the device to useSyncFrameSynchronise USB Frame numbers3.6 Device Enumeration (Connection)
When a USB device is connected to a USB hub, the hub notifies the host (when polled) that a new device is connected. The hub resets the device and signals to the host that the device is ready for communications at address 0x00 (default address).
A number of control transactions are completed to allow the host to communicate with the device; these are listed below:                GetDescriptor (device): Host sends a SETUP packet control sequence to address 0x00 requesting its device description.        SetAddress: Host sets the address on which the device will communicate from now on.        GetDescriptor (device): Re-requests the device descriptor—if this is different to the earlier response an error has occurred;        GetConfiguration (device): Host retrieves all of the configuration information from the device. This means (all) configurations and their properties are described.        SetConfiguration: Host chooses one of the possible configurations and sets the device to use that one.        
After this enumeration phase, the host is able to initiate any of the 4 transaction types to/from the device.
3.7 Keyboard Data Format
Keyboards typically follow the Human Interface Device (HID) class specification [1], to allow standard drivers to access the device. Device drivers for HID devices are typically included with the host operating system.
Using the HID specification ensures devices use interrupt (or control) transactions only. Typically control transactions are used to initialise the device and interrupt transactions used to transfer data. An example keyboard report description is shown in FIG. 9 [1]. Note input/output description is relative to the host—they are reversed relative to the device.
The report above defines the data expected back from the keyboard. Typically the host operating system parses these reports to allow device communications to be understood.
Keyboards typically follow a standard report similar to the one above; they allow 1 byte of information to be transferred from host to keyboard indicating LED status (output), and 8 bytes from keyboard to host indicating key status. The format of those reports is indicated in FIGS. 10 and 11.
The (downstream) input report shown in FIG. 10 is straightforward, 5 bits of information command the current status of the keyboard LEDs. The other 3 bits are simply used for padding.
The (upstream) output report shown in FIG. 11 is more complex than the input report. The first bytes gives the status of the 8 modifier keys (l-ctrl, l-alt, l-shift, l-gui, r-ctrl, r-alt, r-shift, r-gui) with one bit assigned to each. The next byte is reserved and the remaining 6 are used for indicating the USB HID scancodes [3] corresponding to the keys currently pressed. (The state occurring when more than six non-modifier keys are pressed is called the phantom state and is beyond the scope of this document).
In a typical usage scenario the host will initiate an incoming interrupt transfer to poll the keyboard status (request keyboard reports on a regular basis) or initiate an outgoing interrupt transfer to set the LED's status.
3.8 References
    [1] www.usb.org (official USB 1.1 and 2.0 specifications)    [2] USB design by Example, John Hyde, Intel University Press 1999.    [3] USB HID to PS/2 Scan Code Translation Table, Microsoft Corporation, 1999.